package cz.muni.fi.pa165.validate;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.ResourceBundle;
import javax.enterprise.context.ApplicationScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.inject.Named;

/**
 *
 * @author shifty
 */
@ApplicationScoped
@Named
public class EmployeeValidator {
   
    public void validateName(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        ResourceBundle res = ResourceBundle.getBundle("i18n.main", FacesContext.getCurrentInstance().getViewRoot().getLocale());
        if(!(value instanceof String)) {
            FacesMessage message = new FacesMessage(res.getString("error.form.must.string.name"));
            throw new ValidatorException(message); 
        }
        
        
        String val = (String)value;
        
        if(value == null || val.length() < 3) {
            FacesMessage message = new FacesMessage(res.getString("error.form.empty.name"));
            throw new ValidatorException(message); 
        }
        
    }
    
    public void validatePass(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        ResourceBundle res = ResourceBundle.getBundle("i18n.main", FacesContext.getCurrentInstance().getViewRoot().getLocale());
        if(!(value instanceof String)) {
            FacesMessage message = new FacesMessage(res.getString("error.form.must.string.name"));
            throw new ValidatorException(message); 
        }
        
        
        String val = (String)value;
        
        if(value == null || val.length() < 3) {
            FacesMessage message = new FacesMessage(res.getString("error.form.empty.pass"));
            throw new ValidatorException(message); 
        }
        
    }
    
    public void validateBirthDate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        ResourceBundle res = ResourceBundle.getBundle("i18n.main", FacesContext.getCurrentInstance().getViewRoot().getLocale());
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
        Date date = null;
        try {
            date =sdf.parse((String)value);
        }catch(Exception e) {
            FacesMessage message = new FacesMessage(res.getString("error.form.date"));
            throw new ValidatorException(message);
        }
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.YEAR, -15);
        Date youngest = cal.getTime();
        cal.add(Calendar.YEAR, -84);
        Date oldest = cal.getTime();
        if(date.after(youngest) || date.before(oldest)) {
            FacesMessage message = new FacesMessage(res.getString("error.form.youngOrOld"));
            throw new ValidatorException(message);
        } 
    }
}
